import appApi from '@/sheep/api/app';
import { defineStore } from 'pinia';
import $platform from '@/sheep/platform';
import $router from '@/sheep/router';
import user from './user';
import sys from './sys';
import { android_code, baseUrl, h5_code, ios_code, mp_code, wss_url } from '@/sheep/config';
import sheep from '@/sheep';
import { pathToBase64 } from 'image-tools';

const app = defineStore({
  id: 'app',
  state: () => ({
    info: {
      // 应用信息
      name: '', // 商城名称
      logo: '', // logo
      version: '', // 版本号
      cdnurl: '', // 云存储域名
      filesystem: '', // 云存储平台
      user_protocol: {}, // 用户协议
      privacy_protocol: {}, // 隐私协议
      about_us: {}, // 关于我们
      copyright: '', // 版权信息 I
      copytime: '', // 版权信息 II
    },
    code: '',
    platform: {
      payment: [], // 支持的支付方式
      share: {
        methods: [], // 支持的分享方式
        forwardInfo: {}, // 默认转发信息
        posterInfo: {}, // 海报信息
        linkAddress: '', // 复制链接地址
      },
      auto_login: 0, // 自动登陆
      bind_mobile: 0, // 登陆后绑定手机号提醒 (弱提醒，可手动关闭)
    },
    chat: {},
    template: {
      // 店铺装修模板
      basic: {}, // 基本信息
      basic_nc: {}, // 基本信息
      home: {
        // 首页模板
        style: {},
        data: [],
      },
      user: {
        // 个人中心模板
        style: {},
        data: [],
      },
    },
    shareInfo: {}, // 全局分享信息
    has_wechat_trade_managed: 0, // 小程序发货信息管理  0 没有 || 1 有
    is_open_socket: false,// 避免重复链接
    url: wss_url + '/chatsockt',//地址
    data: null,
    timeout: 10000,
    heartbeatInterval: null,
    reconnectTimeOut: null,
    socketTask: null,
    loginInterval: null,
    client_id: '',
    codeScanningResult: {},
    // 元宝记录
    ingotRecords: 0,
    ingotFlag: false,
    ingotInter: null,
    // #ifdef H5
    mode: 'H5',
    // #endif
  }),
  actions: {
    // 获取Shopro应用配置和模板
    async init(templateId = null) {
      //检查网络
      const networkStatus = await $platform.checkNetwork();
      if (!networkStatus) {
        $router.error('NetworkError');
      }

      // 检查配置
      if (typeof baseUrl === 'undefined') {
        $router.error('EnvError');
      }

      const res = await appApi.init(templateId);

      if (res.code === 1) {
        this.info = res.data.app;
        this.code = res.data.code;
        // #ifdef APP-PLUS
        if (sheep.$platform.device.platform.toLocaleLowerCase() == 'ios') {
          this.info.worship_version = this.info.worship_version_3;
        } else {
          this.info.worship_version = this.info.worship_version_2;
        }
        // #endif
        this.platform = res.data.platform;
        this.template = res.data.template;
        this.has_wechat_trade_managed = res.data.has_wechat_trade_managed;
        if (!res.data.template) {
          $router.error('TemplateError');
        }
        this.chat = res.data.chat;

        // 加载主题
        const sysStore = sys();
        sysStore.setTheme();

        // 模拟用户登录
        const userStore = user();
        if (userStore.isLogin) {
          userStore.loginAfter();
        }
        return Promise.resolve(true);
      } else {
        $router.error('InitError', res.msg || '加载失败');
      }
    },
    // webSocket初始化
    async initWebSocket() {
      if (!sheep.$store('user').isLogin) {
        this.loginInterval = setInterval(() => {
          if (sheep.$store('user').isLogin) {
            clearInterval(this.loginInterval);
            this.initWebSocket();
          }
        }, 2000);
        return;
      }
      try {
        return this.connectWebSocket();
      } catch (e) {
        console.log('catch');
        this.is_open_socket = false;
        this.reconnect();
      }
    },
    connectWebSocket() {
      this.socketTask = uni.connectSocket({
        url: this.url,
        success: () => {
          console.log('正准备建立websocket中...');
          // 返回实例
        },
        fail: (err) => {
          console.log('连接失败', err);
        },
      });

      this.socketTask.onOpen((res) => {
        console.log('WebSocket连接正常！');
        clearTimeout(this.reconnectTimeOut);
        clearTimeout(this.heartbeatInterval);
        this.is_open_socket = true;
        this.start();
        // 注：只有连接正常打开中 ，才能正常收到消息
        this.socketTask.onMessage((res) => {
          console.log('收到消息', res);
          let obj = JSON.parse(res.data);
          if (obj.type == 'gift_balance') {
            if (!!this.ingotInter) {
              clearTimeout(this.ingotInter);
            }
            console.log('收到元宝', obj.message);
            this.ingotRecords = obj.message;
            this.ingotFlag = true;
            this.ingotInter = setTimeout(() => {
              this.ingotFlag = false;
              this.ingotInter = null;
            }, 3000);
          }
          // #ifdef APP-PLUS
          let version = '';
          if (sheep.$platform.device.platform.toLocaleLowerCase() == 'ios') {
            version = ios_code;
          } else {
            version = android_code;
          }
          // #endif
          if (obj.type == 'auth') {
            this.client_id = obj.client_id;
            const { data } = sheep.$api.chat.bind({
              client_id: this.client_id,
              // #ifdef H5
              uid: JSON.parse(uni.getStorageSync('user-store')).userInfo.uid,
              // #endif
              // #ifndef H5
              uid: sheep.$store('user').userInfo.uid,
              // #endif
              // #ifdef MP-WEIXIN
              device: 'wechat',
              version: mp_code,
              // #endif
              // #ifdef H5
              device: 'h5',
              version: h5_code,
              // #endif
              // #ifdef APP-PLUS
              device: sheep.$platform.device.osName,
              version,
              // #endif
            });
          } else {
            uni.$emit('checkMessage', obj);
            sheep.$store('AI').setAllSessionList();
          }

          if (obj.type == 'family_apply' || obj.type == 'genealogy_apply') {
            sheep.$store('family').getUnreadMessage(JSON.parse(obj.message));
          }
          if(obj.type == 'user_apply'){
            sheep.$store('family').getUnreadUser(JSON.parse(obj.message));
          }
        });
      });

      this.socketTask.onClose(() => {
        console.log('已经被关闭了');
        this.is_open_socket = false;
        this.reconnect();
      });
    },
    //发送消息
    send(value) {
      // 注：只有连接正常打开中 ，才能正常成功发送消息
      this.socketTask.send({
        data: value,
        async success() {
          // console.log('消息发送成功');
        },
        fail(err) {
          this.reconnect();
        },
      });
    },
    //开启心跳检测
    start() {
      this.heartbeatInterval = setInterval(() => {
        this.data = { type: 'pong', client_id: this.client_id };
        this.send(JSON.stringify(this.data));
      }, this.timeout);
    },
    //重新连接
    reconnect() {
      //停止发送心跳
      clearInterval(this.heartbeatInterval);
      //如果不是人为关闭的话，进行重连
      if (!this.is_open_socket) {
        this.reconnectTimeOut = setTimeout(() => {
          this.initWebSocket();
        }, 3000);
      }
    },
    //外部获取消息
    getMessage(callback) {
      this.socketTask.onMessage((res) => {
        return callback(res);
      });
    },
    setCodeScanningResult(obj) {

    },
    // 加载头像存本地
    async setAvatar(avatar) {
      // #ifdef H5
      const flag = await this.initData();
      console.log('获取到的头像=>', flag);
      if (flag) {
        const { data } = await sheep.$api.family.getDefaultAvatar({
          type: 0,
        });
        for (let index = 0; index < data.length; index++) {
          const obj = await this.getData(data[index].id);
          if (!obj) {
            const url = await pathToBase64(data[index].avatar.indexOf('http') != -1 ? data[index].avatar : sheep.$store('AI').nc_image + data[index].avatar);
            await this.setData({
              name: data[index].id,
              url: url,
              url_origin: data[index].avatar.indexOf('http') != -1 ? data[index].avatar : sheep.$store('AI').nc_image + data[index].avatar,
            });
          }
        }
      }
      // #endif

      // #ifdef APP-PLUS
      const { data } = await sheep.$api.family.getDefaultAvatar({
        type: 0,
      });
      console.log(data);
      for (let index = 0; index < data.length; index++) {
        if (!uni.getStorageSync(`avatar${data[index].id}`)) {
          uni.downloadFile({
            url: sheep.$store('AI').nc_image + data[index].avatar,
            success: (res) => {
              uni.saveFile({
                tempFilePath: res.tempFilePath,
                success: (res) => {
                  console.log(res);
                  uni.setStorageSync(`avatar${data[index].id}`, sheep.$store('AI').nc_image + data[index].avatar);
                },
              });
            },
          });
        }
      }
      // #endif

      // #ifdef MP-WEIXIN
      const { data } = await sheep.$api.family.getDefaultAvatar({
        type: 0,
      });
      data.forEach(item => {
        if (!uni.getStorageSync(`avatar${item.id}`)) {
          uni.setStorageSync(`avatar${item.id}`, sheep.$store('AI').nc_image + item.avatar);
          uni.downloadFile({
            url: sheep.$store('AI').nc_image + item.avatar,
          });
        }
      });
      // #endif
    },
    // #ifdef H5
    async initData() {
      return new Promise((resolve, reject) => {
        const request = window.indexedDB.open('avatar_sql', 1);
        request.onerror = () => {
          console.log('数据库打开失败');
          reject();
        };
        request.onsuccess = (event) => {
          this.db = event.target.result;
          resolve(true);
        };
        request.onupgradeneeded = (event) => {
          this.db = event.target.result;
          if (!this.db.objectStoreNames.contains('avatar_sql')) {
            const treeSpectrumCache = this.db.createObjectStore('avatar_sql', { keyPath: 'id', autoIncrement: true });
            treeSpectrumCache.createIndex('name', 'name', { unique: true });
            treeSpectrumCache.createIndex('url', 'url', { unique: true });
            treeSpectrumCache.createIndex('url_origin', 'url_origin', { unique: true });
          }
          resolve(true);
        };
      });
    },
    async setData(data) {
      return new Promise((resolve, reject) => {
        this.db.transaction(['avatar_sql'], 'readwrite').objectStore('avatar_sql').add(data);
        resolve(true);
      });
    },
    async getData(name) {
      return new Promise((resolve, reject) => {
        const request = this.db.transaction(['avatar_sql'], 'readwrite').objectStore('avatar_sql').index('name').get(name);
        request.onsuccess = (event) => {
          if (!!event.target.result) {
            resolve(event.target.result.url);
          } else {
            resolve(false);
          }
        };
        request.onerror = (event) => {
          reject(false);
        };
      });
    },
    // #endif
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'app-store',
      },
    ],
  },
});

export default app;
